<?php

namespace app\api\controller;

use app\admin\framework\validate\UserValidate;
use app\common\model\User;
use app\common\service\UserService;
use app\common\utils\aliyun\Sms;
use app\common\utils\Is;
use taoser\exception\ValidateException;
use taoser\facade\Validate;

class UserController
{
    protected $noNeedLogin = ['login', 'register', 'passwordReset'];
    
    public function profile()
    {
        $userInfo = UserService::get();
        $userInfo->roleIds = UserService::getRoleIds($userInfo->id);
        return apiSuccess(data: $userInfo);
    }
    
    public function login()
    {
        $data = request()->post();
        
        $where = [];
        if (empty($data['username']))
            return apiError('请输入账号');
        
        if (empty($data['password']))
            return apiError('请输入账号');
        
        if (Is::mobile($data['username'])) {
            $where[] = ['mobile', '=', $data['username']];
        } else {
            $where[] = ['username', '=', $data['username']];
        }
        
        $userInfo = User::where($where)->find();
        if (empty($userInfo) || !password_verify($data['password'], $userInfo->password)) {
            return apiError('账号不存在或密码错误');
        }
        if (empty($userInfo['status'])) {
            return apiError('你的账号已被禁用');
        }
        
        if ($userInfo['user_type'] === 1) {
            // 管理员登录
            // 查看是否有登录权限
            $roles = UserService::getRoleIds($userInfo->id);
            if (!in_array(3, $roles)) {
                return apiError('抱歉，你没该权限');
            }
        }
        
        
        // $userInfo->token = md5(uniqid());
        $userInfo->last_login_ip = request()->getRealIp();
        $userInfo->last_login_time = date('Y-m-d H:i:s', time());
        $userInfo->save();
        $token = UserService::generateToken($userInfo->id);
        return apiSuccess("登录成功", [
            'token' => $token
        ]);
    }
    
    
    public function register()
    {
        $data = request()->post();
        
        $validate = Validate::rule([
            'mobile' => 'require',
            'password' => 'require',
            'verification_code' => 'require'
        ])->message([
            'mobile.require' => '请输入手机号!',
            'password.require' => '请输入您的密码!',
            'verification_code.require' => '请输入数字验证码!'
        ]);
        
        if (!$validate->check($data)) {
            return apiError($validate->getError());
        }
        
        $message = Sms::checkVerificationCode($data['mobile'], $data['verification_code']);
        if (!empty($message)) {
            return apiError($message);
        }
        
        if ($data['password'] != $data['repassword']) {
            return apiError('两次密码输入不一致！');
        }
        
        $user = new User();
        $userInfo = $user->where('mobile', '=', $data['mobile'])->find();
        
        if (empty($userInfo)) {
            // 注册
            $dateTime = date('Y-m-d H:i:s', time());
            $user->username = '匿名用户_' . $data['mobile'];
            $user->nickname = '匿名用户_' . $data['mobile'];
            $user->mobile = $data['mobile'];
            $user->password = password_hash($data['password'], PASSWORD_DEFAULT);
            $user->register_ip = request()->getRealIp($safe_mode = true);
            $user->register_time = $dateTime;
            $user->user_type = 2;
            $user->save();
        } else {
            return apiError('该账号已存在');
        }
        return apiSuccess('注册成功');
    }
    
    
    // 修改用户信息
    public function save()
    {
        $data = request()->only(['nickname', 'email']);
        
        $validate = Validate::rule([
            'email' => 'require',
            'nickname' => 'require'
        ])->message([
            'email.require' => '请输入电子邮箱!',
            'nickname.require' => '请输入姓名!',
        ]);
        
        if (!$validate->check($data)) {
            return apiError($validate->getError());
        }
        
        UserService::update($data);
        return apiSuccess('保存成功');
    }
    
    
    // 设置头像
    public function setAvatar()
    {
        if ($avatar = request()->post('avatar', '')) {
            UserService::update(['avatar' => $avatar]);
            return apiSuccess('保存成功');
        } else {
            return apiError('请选择头像');
        }
    }
    
    // 绑定手机号码
    public function bindMobile()
    {
        $data = request()->post();
        $validate = Validate::rule([
            'mobile' => 'require|unique:user,mobile',
            'verification_code' => 'require'
        ])->message([
            'mobile.require' => '请输入您的手机号!',
            'mobile.unique' => '手机号已经存在！',
            'verification_code.require' => '请输入数字验证码!'
        ]);
        
        if (!$validate->check($data)) {
            return apiError($validate->getError());
        }
        
        if (!Is::mobile($data['mobile'])) {
            return apiError('请输入正确的手机格式!');
        }
        
        $message = Sms::checkVerificationCode($data['mobile'], $data['verification_code']);
        if (!empty($message)) {
            return apiError($message);
        }
        
        UserService::update(['mobile' => $data['mobile']]);
        
        return apiSuccess("绑定成功");
    }
    
    /**
     * 重置密码
     * @return \support\Response
     */
    public function passwordReset()
    {
        
        $validate = Validate::rule([
            'mobile' => 'require',
            'password' => 'require',
            'verification_code' => 'require'
        ])->message([
            'mobile.require' => '请输入手机号!',
            'password.require' => '请输入您的密码!',
            'verification_code.require' => '请输入数字验证码!'
        ]);
        
        $data = request()->post();
        if (!$validate->check($data)) {
            return apiError($validate->getError());
        }
        
        if (!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)/', $data['password']) && strlen($data['password']) >= 8 && strlen($data['password']) <= 16) {
            return apiError('密码需字母+数字8-16位之间');
        }
        
        if (!Is::mobile($data['mobile'])) {
            return apiError('请输入正确的手机格式!');
        }
        
        $message = Sms::checkVerificationCode($data['mobile'], $data['verification_code']);
        if (!empty($message)) {
            return apiError($message);
        }
        
        
        User::where('mobile', $data['mobile'])->update([
            'password' => password_hash($data['password'], PASSWORD_DEFAULT)
        ]);
        
        return apiSuccess("密码重置成功,请使用新密码登录!");
    }
    
}